import { useTranslation } from 'react-i18next';
import moment from 'moment';
import {
  Grid,
  Typography,
  TableContainer,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  Box,
  useTheme
} from '@mui/material';

// Icons
import ReceiptLongIcon from '@mui/icons-material/ReceiptLong';
import DescriptionIcon from '@mui/icons-material/Description';
import AccountBalanceIcon from '@mui/icons-material/AccountBalance';
import CalendarTodayIcon from '@mui/icons-material/CalendarToday';
import PaymentsIcon from '@mui/icons-material/Payment';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import PendingIcon from '@mui/icons-material/Pending';
import LaunchIcon from '@mui/icons-material/Launch';

// Styled Components
import {
  StyledPaper,
  StyledAppButton,
  StyledTable
} from 'components/objects/StyledComponents';

/**
 * PaymentHistoryDesktop component that displays invoice data in table view
 * 
 * @param {Object} props
 * @param {Array} props.invoicesData - Array of invoice data objects
 * @param {string} props.currency - Currency code for formatting
 * @param {Function} props.formatMoney - Utility function to format currency
 */
const PaymentHistoryDesktop = ({
  invoicesData = [],
  currency = 'USD',
  formatMoney
}) => {
  const { t } = useTranslation();
  const theme = useTheme();
  const isDarkMode = theme.palette.mode === 'dark';

  // Filter invoices to only show paid or open ones
  const filteredInvoices = invoicesData.filter(invoice => 
    invoice.status === "paid" || invoice.status === "open"
  );

  // Format date from Unix timestamp
  const formatDate = (unixTimestamp) => {
    return moment.unix(unixTimestamp).format("DD/MM/YYYY");
  };

  // Header cell component for table headers
  const HeaderCell = ({ children, icon, ...props }) => (
    <TableCell 
      {...props} 
      sx={{ 
        ...(props?.sx || {}),
        color: isDarkMode ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.6)'
      }}
    >
      {icon && (
        <Box sx={{ textAlign: 'center', mb: 0.5 }}>
          {icon}
        </Box>
      )}
      {children}
    </TableCell>
  );

  // Cell with icon component for table cells with icons
  const IconCell = ({ icon, text }) => (
    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
      {icon}
      <Typography>{text}</Typography>
    </Box>
  );

  return (
    <Grid item xs={12}>
      <StyledPaper darkMode={isDarkMode} sx={{ p: 3 }}>
        {/* Payment History Header */}
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
          <ReceiptLongIcon 
            color="primary" 
            sx={{ fontSize: 32, mr: 2 }}
          />
          <Typography variant="h5" component="h1">
            {t("dashboardPage.paymentHistory")}
          </Typography>
        </Box>

        {/* Table View */}
        <TableContainer>
          <StyledTable darkMode={isDarkMode}>
            <TableHead>
              <TableRow>
                <HeaderCell 
                  icon={<DescriptionIcon sx={{ fontSize: 20 }} />}
                >
                  {t("dashboardPage.paymentId")}
                </HeaderCell>
                <HeaderCell 
                  icon={<AccountBalanceIcon sx={{ fontSize: 20 }} />}
                >
                  {t("dashboardPage.status")}
                </HeaderCell>
                <HeaderCell 
                  icon={<CalendarTodayIcon sx={{ fontSize: 20 }} />}
                >
                  {t("dashboardPage.date")}
                </HeaderCell>
                <HeaderCell 
                  icon={<PaymentsIcon sx={{ fontSize: 20 }} />}
                >
                  {t("dashboardPage.total")}
                </HeaderCell>
                <HeaderCell>
                  {t("dashboardPage.actions")}
                </HeaderCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {filteredInvoices.map((invoice, i) => (
                <TableRow 
                  key={`table-${i}`}
                  sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                >
                  <TableCell>
                    <IconCell 
                      icon={<DescriptionIcon sx={{ fontSize: 20 }} />}
                      text={invoice.number}
                    />
                  </TableCell>
                  <TableCell>
                    <IconCell 
                      icon={
                        invoice.paid ? (
                          <CheckCircleIcon color="success" sx={{ fontSize: 20 }} />
                        ) : (
                          <PendingIcon color="warning" sx={{ fontSize: 20 }} />
                        )
                      }
                      text={invoice.paid ? t("dashboardPage.paid") : t("dashboardPage.toPay")}
                    />
                  </TableCell>
                  <TableCell>
                    <IconCell 
                      icon={<CalendarTodayIcon sx={{ fontSize: 20 }} />}
                      text={formatDate(invoice.created)}
                    />
                  </TableCell>
                  <TableCell>
                    <IconCell 
                      icon={<PaymentsIcon sx={{ fontSize: 20 }} />}
                      text={formatMoney("it", currency, invoice.total / 100)}
                    />
                  </TableCell>
                  <TableCell>
                    {invoice.hosted_invoice_url && invoice.status === "open" && (
                      <StyledAppButton
                        darkMode={isDarkMode}
                        component="a"
                        href={invoice.hosted_invoice_url}
                        target="_blank"
                        rel="noreferrer"
                        startIcon={<LaunchIcon />}
                        size="small"
                        variant="outlined"
                        sx={{ px: 1 }}
                      >
                        {t("dashboardPage.toPay")}
                      </StyledAppButton>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </StyledTable>
        </TableContainer>
      </StyledPaper>
    </Grid>
  );
};

export default PaymentHistoryDesktop;